<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>微信验证</title>
</head>
<body></body>
<script src="wx.config.js"></script>
<script>
    const code = getQueryString('code');


    const href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + locationHref + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechart_redirect';

    if (!code) {
        window.location.replace(href);
    } else {
        console.log(code);

        validateUser().then(res => {
            localStorage.setItem('wxInfo', JSON.stringify(res.data));
            window.location.replace(`${location.origin}/home`);
        })
    }
    //
    //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=SERVICEAPPID&secret=SERVICESECRET


    function validateUser() {

        return new Promise((resolve, reject) =>{
            ajax('get','https://api-ds114.haichuang.pro/common/mp/user/register',{code: code}).then(res => {
                //if(data.subscribe != 1){
                   // return alert('未关注公众号');
                    // window.location.replace('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg3MDA2ODI5Nw==&scene=126&bizpsid=0#wechat_redirect');
                    // return;
                //}
                resolve(res);
            });
        });
    }

    function ajax(method, uri, data) {
        return new Promise((resolve, reject) => {
            let xmlHttp = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
            let params = [];
            for (let key in data) {
                params.push(key + '=' + data[key]);
            }
            let postData = params.join('&');
            if (method.toUpperCase() === 'POST') {
                xmlHttp.open(method, uri, true);
                xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
                xmlHttp.send(postData);
            } else if (method.toUpperCase() === 'GET') {
                xmlHttp.open(method, uri + '?' + postData, true);
                xmlHttp.send();
            }
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    //opt.success();
                    resolve(JSON.parse(xmlHttp.responseText))
                }
            };
        });

    }



    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

</script>
</html>
